package com.googlecode.cardamomo.ermodel;

import java.util.Vector;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;

@XmlType(namespace=DataType.CARDAMOMO_NAMESPACE,
		propOrder={"name", "unique", "filter", "keys" })
@XmlRootElement
public class Index {

	boolean unique = false;
	String name;
	String filter;
	Vector<Key> keys = new Vector<Key>();

	@XmlAttribute(name="name",required=true)
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
//		System.err.println("Index.setname "+name);
		this.name = name;
	}
	
	@XmlElement
	public String getFilter() {
		return filter;
	}

	public void setFilter(String filter) {
		this.filter = filter;
	}

	@XmlAttribute(name="unique")
	public boolean isUnique() {
		return unique;
	}

	public void setUnique(boolean unique) {
		this.unique = unique;
	}

	@XmlElementWrapper(name="keys")
	@XmlElement(name="key")
	public Vector<Key> getKeys() {
		return keys;
	}

	public void setKeys(Vector<Key> columns) {
		keys = columns;
	}

	@XmlTransient
	public int getKeyCount()
	{
		if (keys == null)
			return 0;
		return keys.size();
	}

	public Key getKey(int i)
	{
		if (keys == null)
			return null;
		for (int j = 0; j < keys.size(); j++)
			if (keys.get(j).getOrder() == i)
				return keys.get(j);
		return null;
	}

	@XmlTransient
	public String getKeyNames() {
		StringBuffer sb = new StringBuffer();
		if (keys == null)
			return "";
		for (int i = 0; i < keys.size(); i++ ) {
			Key k = keys.get(i);
			if (k == null) continue;
			if (sb.length() > 0) sb.append(", ");
			sb.append(k.getColumnName());
		}
		return sb.toString();
	}

	public void addKey(Key k)
	{
		keys.add(k);
	}
	
	public void addKey(short ordinal, String cname, boolean asc) {
		Key km = new Key(ordinal, cname, asc);
		keys.add(km);
	}
	
	@Override
	public String toString() {
		return "Index "+getName()+":"+getKeys();
	}
	
	@Override
	public boolean equals(Object arg0) {
		Index im = (Index) arg0;
		
		if (im.getKeyCount() != getKeyCount()) return false;
		for (int ix = 0; ix < getKeyCount(); ix++) {
			Key cm = im.getKey(ix+1);
			Key thiscm = getKey(ix+1);
			if (!cm.equals(thiscm)) return false;
		}
		return super.equals(arg0);
	}

	public boolean equivalent(Index im) {
		
		if (im.getKeyCount() != getKeyCount()) return false;
		for (int ix = 0; ix < getKeyCount(); ix++) {
			Key cm = im.getKey(ix+1);
			Key thiscm = getKey(ix+1);
			if (!cm.equals(thiscm)) return false;
		}
		return true;
	}

	public boolean contains(String name) {
		for (Key key : getKeys()) {
			if (key.getColumnName().equals(name))
				return true;
		}
		return false;
	}
}
